<template>
  <div class="title">账号列表</div>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="selection" width="55" />
    <el-table-column label="账号" width="292">
      <template #default="scope">{{ scope.row.account }}</template>
    </el-table-column>
    <el-table-column property="userGroup" label="用户组" width="292" />
    <el-table-column
      label="创建时间"
      width="240"
      show-overflow-tooltip
    >
      <template #default="scope">
        {{ formatTime(scope.row.ctime) }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="openEditDialog(scope.row)" style="background-color: #409eff; color: white;">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <!-- 使用el-dialog组件 -->
  <el-dialog
    v-model="dialog"
    title="修改账号信息"
    :before-close="handleClose"
    width="400px"
    :modal="true"
    :modal-append-to-body="true"
    :append-to-body="true"
  >
    <div class="demo-drawer__content">
      <el-form :model="form">
        <el-form-item label="账号名" :label-width="formLabelWidth">
          <el-input v-model="form.account" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户组" :label-width="formLabelWidth">
          <el-select
            v-model="form.userGroup"
            placeholder="请选择用户组"
          >
            <el-option label="超级管理员" value="超级管理员" />
            <el-option label="普通管理员" value="普通管理员" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitEdit">
          确定
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { getAccountList, editAccount, deleteAccount } from '../../api/account';
import dayjs from 'dayjs';
import { ElMessageBox, ElDialog } from 'element-plus';

// 新增 dialog 变量的声明和初始化
const dialog = ref(false);
const currentEditId = ref(null);

interface User {
  id: number;
  account: string;
  userGroup: string;
  ctime: string | number;
}

const tableData = ref<User[]>([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

const fetchData = async () => {
  const data = {
    currentPage: currentPage.value,
    pageSize: pageSize.value
  };
  try {
    const res = await getAccountList(data);
    console.log(res);
    tableData.value = res.data;
    total.value = res.total;
  } catch (error) {
    console.error('获取账号列表失败:', error);
  }
};

onMounted(() => {
  fetchData();
});

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  fetchData();
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  fetchData();
};

// 修改函数名与逻辑
const openEditDialog = (row: User) => {
  currentEditId.value = row.id;
  form.value.account = row.account;
  form.value.userGroup = row.userGroup;
  dialog.value = true;
};

const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该账号吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const res = await deleteAccount(id);
    console.log(res);
    fetchData();

  } catch (error) {
    if (error!== 'cancel') {
      console.error('删除账号失败:', error);
    }
  }
};

const formatTime = (time: string | number) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
};

// 新增 handleClose 函数
const handleClose = () => {
  dialog.value = false;
};

// 新增 cancelForm 函数
const cancelForm = () => {
  dialog.value = false;
};

// 新增 loading 变量和 onClick 函数
const loading = ref(false);
const form = ref({
  account: '',
  userGroup: ''
});
const formLabelWidth = ref('80px');

const submitEdit = async () => {
  loading.value = true;
  const formdata = {
    id: currentEditId.value,
    account: form.value.account,
    userGroup: form.value.userGroup
  }
  try {
    const res = await editAccount(formdata);
    console.log(res);
    fetchData();
    dialog.value = false;
  } catch (error) {
    console.error('编辑账号失败:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.title {
  width: 100%;
  height: 50px;
  font-size: 20px;
  color: #333;
  line-height: 50px;
  padding-left: 20px;
  text-align: left;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-table__cell) {
  height: 47px;
  line-height: 47px;
  padding: 0;
  font-weight: 100;
  font-size: 14px;
}

:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  position: sticky;
  top: 0;
  background: white;
  z-index: 1;
}

</style>